<template>
    <div class="video-container" @mouseenter="ShowControls=true" @mouseleave="ShowControls=false" ref="videoContainer">
        <vueDanmaku :danmus="danmus" :autoplay="false" :channels="2" style="height: 100px;" class="danmu" ref="danmuku"></vueDanmaku>
        <video :src="attchFile(gid == undefined ? 0 : gid,filename)" autoplay ref="videoPlayer"
        @click="changeVideoStatus" @timeupdate="updateProgressBar">
        </video>

        <transition name="fade">
        <div class="video-controls" v-show="ShowControls" >
            <div class="time-show">
                <span v-show="ShowTime" ref="timeDisplay">{{ nowTime }}</span>
            </div>
            <div class="video-progress" @mousemove="showTime" @mouseleave="ShowTime=false">
                <progress :class="{'progress-bar':!ShowTime,'progress-bigbar':ShowTime}"
                 max="100" value="0" ref="progressBar" @click="changeVideoTime" ></progress>
            </div>
            <div class="video-bottom">
                <div class="bottom-left">
                  <div @click="changeVideoStatus">
                    <gIcon v-if="isPaused"  :icon="iconList.Play"></gIcon>
                    <gIcon v-else="!isPaused"  :icon="iconList.Stop" @click=""></gIcon>
                  </div>
                </div>
                <div class="bottom-right">
                   <div class="volume-controls"  @mouseenter="showVolume(true)" @mouseleave="showVolume(false)" >
                    <transition name="fade">
                    <div class="volume-control" v-show="ShowVolume">
                        <span v-if="Volume" style="color: white;font-size: 12px;margin-bottom: 2px;">{{ VolumeValue }}</span>
                        <div id="volume-level" @click="changeVolume">
                            <div id="level" ref="volumeLevel">
                            </div>
                        </div>
                   </div>
                   </transition>
                   <div @click="closeOrOpenVolume">
                     <gIcon v-if="Volume" :icon="iconList.Sound"></gIcon>
                     <gIcon v-else="!Volume" :icon="iconList.NoSound"></gIcon>
                   </div>
                  </div>

                  <div class="fullScreen" @click="toFullScreen">
                    <gIcon v-if="!isFullScreen" :icon="iconList.FullScreen"></gIcon>
                    <gIcon v-else="isFullScreen" :icon="iconList.NoFullScreen"></gIcon>
                  </div>
                </div>
            </div>
        </div>
        </transition>
    </div>
</template>

<script lang="ts">
import { defineComponent,getCurrentInstance, onBeforeUnmount, onMounted , ref, toRefs, watch } from 'vue';
import { HttpRequest } from '../request/request';
import gIcon from '../components/gIcon.vue'
import vueDanmaku from 'vue3-danmaku'
import { icons } from '../assets/icons/icon'
import GIcon from '../components/gIcon.vue';
import { userInfo } from '@/stores/user';

export default defineComponent({
    components:{
        gIcon,
        vueDanmaku
    },
    props:{
        resource:String,
        sendedDanmu:String,
        gid:Number
    },
    emits:["changeWatchNum"],
    setup(props){
        const proxy = getCurrentInstance()?.proxy;
        const {resource}=toRefs(props);
        const gid=toRefs(props).gid;
        const filename = ref("op.webm");
        const vid = ref(0);
        const uid = userInfo().uid;
        const {sendedDanmu}=toRefs(props);
        const video=ref<HTMLVideoElement>();
        const progress=ref<HTMLProgressElement>();
        const timeDisplay=ref<HTMLElement>();
        const volumeLevel=ref<HTMLElement>();
        const isPaused=ref(true);
        const Volume=ref(true);
        const ShowControls=ref(true);
        const ShowTime=ref(false);
        const nowTime=ref("00:00");
        const ShowVolume=ref(false);
        const VolumeValue=ref(100);
        const isFullScreen=ref(false);
        const danmus=ref<string[]>(["弹幕来咯"]);
        const danmuMap=ref<Map<number,string[]>>(new Map<number,string[]>());
        const playedDanmu=ref<Set<number>>(new Set<number>);
        const danmuku=ref();
        danmuMap.value.set(2,["第二秒弹幕"]);
        danmuMap.value.set(4,["第四秒弹幕"]);
        const iconList=({
            Play:icons.play,
            Stop:icons.stop,
            Sound:icons.sound,
            NoSound:icons.nosund,
            FullScreen:icons.fullscreen,
            NoFullScreen:icons.nofullscreen
        })

        onMounted(()=>{
            getVideoDanmu();
            video.value=proxy?.$refs.videoPlayer as HTMLVideoElement;
            progress.value=proxy?.$refs.progressBar as HTMLProgressElement;
            video.value.play();
            isPaused.value=video.value.paused;
            window.addEventListener('keydown',handleKeyDown);
            danmuku.value=proxy?.$refs.danmuku;
            if(!video.value.paused) danmuku.value.play();
            window.addEventListener('beforeunload',()=>{
            window.removeEventListener('keydown',handleKeyDown);
        })
    });


        watch(resource,()=>{
                proxy?.$nextTick(()=>{
                    filename.value = resource.value == undefined ? "" : resource.value;
                    video.value?.play();
                })  
        })
        watch(sendedDanmu,()=>{
            console.log(sendedDanmu.value);
            if(sendedDanmu != undefined && sendedDanmu.value!=="" && sendedDanmu.value !== null){
                danmuku.value.add(sendedDanmu.value);
                HttpRequest.sendDanmu(vid.value,uid,sendedDanmu.value,Math.floor(video.value.currentTime/2)*2);
                sendedDanmu.value = "";
            }
        })
        



        function updateProgressBar(){
            
            const currentTime=video.value.currentTime;
            const duratioin=video.value.duration;
            progress.value.value=(currentTime/duratioin) * 100;
            isPaused.value=video.value.paused;
            const start = Math.floor(currentTime/2)*2;
            if(!playedDanmu.value.has(start)){
                playedDanmu.value.add(start);
                const dan = danmuMap.value.get(start);
                if(dan!==undefined && dan !== null){
                    danmus.value.push(...dan);
                    if(video.value?.played) danmuku.value.play();
                }

            }

        }

        function changeVideoStatus(){
            if(video.value.paused){
                video.value.play();
                danmuku.value.play();
                isPaused.value=false;
            }else{
                video.value.pause();
                danmuku.value.pause();
                isPaused.value=true;
            }
        }

        function changeVideoTime(e){
            danmuku.value.stop();
            danmus.value.splice(0,danmus.value.length);
            playedDanmu.value.clear();
            const progressBar=e.target;
            const clickX=e.clientX-progressBar.getBoundingClientRect().left;
            const clickPercentage = (clickX / progressBar.offsetWidth) * 100;

            video.value.currentTime=(video.value.duration) * clickPercentage/100;
            progress.value.value=clickPercentage;
        }

        function quickChangeVideoTime(seconds){
            if(video.value.currentTime+seconds>video.value.duration){
                video.value.currentTime=video.value.duration;
            }
            else if(video.value.currentTime+seconds<0){
                video.value.currentTime=0;
            }
            else {
                video.value.currentTime+=seconds;
            }

        }
        function showTime(e){
            const progressBar=e.target;
            const overX=e.clientX-progressBar.getBoundingClientRect().left;
            const newPosition=((overX-12)/progressBar.offsetWidth) * 100;
            const time=video.value.duration * (overX/progressBar.offsetWidth);
            const minutes=Math.floor(time/60);
            const seconds=Math.floor(time%60);
            timeDisplay.value=proxy.$refs.timeDisplay as HTMLElement;
            timeDisplay.value.style.left=`${newPosition}%`;
            nowTime.value=`${String(minutes).padStart(2,'0')}:${String(seconds).padStart(2,'0')}`;
            ShowTime.value=true;
        }


        function closeOrOpenVolume(){
            volumeLevel.value=proxy.$refs.volumeLevel as HTMLElement;
            if(video.value.volume===0){
                video.value.volume=VolumeValue.value/100;
                volumeLevel.value.style.height=`${VolumeValue.value}%`;
                Volume.value=true;
            }else{
                video.value.volume=0;
                volumeLevel.value.style.height='0%';
                Volume.value=false;
            }
        }

        function changeVolume(event){
            volumeLevel.value=proxy.$refs.volumeLevel as HTMLElement;
            const volumeBar=event.target;
            const positionY=volumeBar.getBoundingClientRect().bottom-event.clientY;
            const newLevel=Math.min((positionY/volumeBar.offsetHeight) * 100,100);
            VolumeValue.value=Math.floor(newLevel);
            video.value.volume=newLevel/100;
            volumeLevel.value.style.height=`${newLevel}%`;
        }

        function showVolume(isShow){
            if(isShow)
                ShowVolume.value=true;
            else
                ShowVolume.value=false;

        }
        function handleKeyDown(event){
            if(event.key===" "){
                event.preventDefault();
                changeVideoStatus();
            }
            else if(event.key==="ArrowRight"){
                danmuku.value.reset();
                playedDanmu.value.clear();
                quickChangeVideoTime(3);
            }
            else if(event.key==="ArrowLeft"){
                danmuku.value.reset();
                playedDanmu.value.clear();
                quickChangeVideoTime(-3);
            }

        }

        function toFullScreen(){
        
            const video=proxy?.$refs.videoContainer as any;
            if(!document.fullscreenElement)
            {
                if (video.requestFullscreen) {
                    video.requestFullscreen();
                } else if (video.mozRequestFullScreen) {
                    video.mozRequestFullScreen();
                } else if (video.webkitRequestFullscreen) {
                    video.webkitRequestFullscreen();
                }else if (video.msRequestFullscreen) {
                    video.msRequestFullscreen();
                } else{
                    console.log("浏览器不支持全屏")
                }
                isFullScreen.value=true
            }
            else {
                if(document.exitFullscreen){
                    document.exitFullscreen();
                }else if (video.webkitCancelFullScreen) {
                    video.webkitCancelFullScreen();
                 } else if (video.mozCancelFullScreen) {
                    video.mozCancelFullScreen();
                } else if (video.msExitFullscreen) {
                    video.msExitFullscreen();
                } else console.log("浏览器不支持取消全屏")

                isFullScreen.value=false;
            }
        }

        async function getVideoDanmu() {
            const result = await HttpRequest.getVideoDanmu(gid.value,filename.value.substring(0,2)) as responseBody;
            if(result.success){
                vid.value = result.data.vid;
                for(var item of result.data.danmus){
                    if(!danmuMap.value.has(item.time)) danmuMap.value.set(item.time,[]);
                    danmuMap.value.get(item.time)?.push(item.content);
                }
            }
            else{
                (proxy as any).$message({
                message:result.msg,
                type:result.type
                })
            }
        }




        return {
            attchFile:HttpRequest.attchFile,
            updateProgressBar,
            changeVideoStatus,
            changeVideoTime,
            iconList,
            isPaused,
            Volume,
            ShowControls,
            ShowTime,
            nowTime,
            showTime,
            closeOrOpenVolume,
            handleKeyDown,
            ShowVolume,
            showVolume,//改变音量图标
            changeVolume,
            VolumeValue,
            toFullScreen,
            isFullScreen,
            danmus,
            filename,
        }
    }
})
</script>

<style scoped>

.video-container{
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    width: auto;
    height: 400px;
    @media(max-width: 1200px) {
        height: 350px;
    }
    @media(min-width: 1500px) {
        height: 450px;
    }
    video{
        width: 100%;
        height: 100%;
        object-fit: fill;
        border-radius: 10px;
    }
}
.danmu{
    left: 0;
    right: 0;
    top: 30px;
    z-index: 200;
    position: absolute;
}

.video-controls{
    right: 0;
    left: 0;
    padding: 10px;
    position: absolute;
    bottom: 0;
    transition: opacity 0.5s;
    z-index: 100;
    background: rgba(0, 0, 0, 0.08);
}


.time-show{
    position: relative;
    width: 100%;
    height: 10px;
    margin-bottom: 10px;
    top: 0;
    span{
        position: absolute;
        font-size: small;
        color: white;
    }
}
.video-progress{
    height: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    .progress-bar{
    padding: 0 ;
    width: 100%;
    height: 2px;
    background-color: transparent;
    transition: height 0.2s;
    border-radius: 20%;
    cursor: pointer;
}


.progress-bigbar{
    height: 5px;
    width: 100%;
    background-color: transparent;
    transition: height 0.2s;
    border-radius: 50%;
    cursor: pointer;
}
progress::-webkit-progress-value {
  background-color: #33a3dc; 
}
progress::-moz-progress-bar {
  background-color: #33a3dc;
}
progress::-ms-fill {
  background-color: #33a3dc;
}


}

.video-bottom{
    display: flex;
    position: relative;
    padding: 0;
    .bottom-left{
        width: 200px;
        display: flex;
        justify-content: space-between;
        padding: 0;
    }
    .bottom-right{
        display: flex;
        justify-content: space-between;
        width: 200px;
        height: 100%;
        position: absolute;
        right: 20px;
        bottom: 0;
        padding: 0;
        .volume-controls{
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            align-items: center;
            padding: 0;
        }
        .volume-control{
            width: 25px;
            height: 100px;
            margin-bottom: 10px;
            background-color:rgba(0, 0, 0, 0.5);
            transition: opacity 0.3s;
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            align-items: center;
            border-radius: 5%;
            cursor: pointer;
            padding: 0;
        }

        #volume-level{
            width: 5px;
            height: 70px;
            margin-bottom: 10px;
            background-color:white;
            border-radius: 2px;
            padding: 0;
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            align-items: center;
            #level{
                width: 100%;
                height: 100%;
                background-color: #009ad6;
                padding: 0;
                border-radius: 2px;
                position: relative;
            }

            #level::before{
                content: "";
                width: 12px;
                height: 12px;
                left: -4px;
                top: -4px;
                position: absolute;
                background-color: #009ad6;
                border-radius: 50%;
            }
        }

    }
    
}

video:-webkit-full-screen::-webkit-media-controls,
video:fullscreen::-webkit-media-controls {
  display: none; 
}

.fade-enter-active{
    transition: opacity 0.1s;
}
.fade-leave-active {
  transition: opacity 0.6s;
}
.fade-enter-active, .fade-leave-active  {
  opacity: 0;
}
</style>